const Controller = require('egg').Controller;
const user_list = [
    {id:1,name:'张飞'},
    {id:2,name:'关羽'},
    {id:3,name:'赵云'}
];

class FruitsController extends Controller{

    async index(){
        let container = "";
        for(var i=0;i< user_list.length;i++){
            container  +=`<tr><td>${user_list[i]['id']}</td><td>${user_list[i]['name']}</td><td><a href="/edit/${user_list[i]['id']}">修改</a><form action="/fruits/${user_list[i]['id']}" method="delete"><input type="submit" value="删除" /></form></td></tr>`; 
        }
        container = `<a href="fruits/new">添加</a><table border='1'><tr><td>ID</td><td>姓名</td><td>操作</td></tr>` + container + `</table>`;
        this.ctx.body = container;
    }
    async new(){
        this.ctx.body = `<form action="/fruits" method="post"><input type="text" name="name" value="" /><input type="submit" value="添加" /></form>`;
    }

    async create(){
        let user = this.ctx.request.body;
        user.id = this.getId();
        user_list.push(user);
        this.ctx.redirect("/fruits");
    }

    async destroy(){
        let id = this.ctx.request.body;
        this.ctx.body = id;
    }

    async toEdit(){
        let id= this.ctx.params.id;
        let item = {};
        for(var i=0;i<user_list.length;i++){
            if(id == user_list[i]['id']){
                item = user_list[i];
            }
        }
        let str = `<form action="/save" method="post"><input type="hidden" name="id" value="${item.id}" /><input type="text" value="${item.name}" name="name" /><input type="submit" value="保存" /></form>`;
        this.ctx.body = str;

    }

    async toSave(){
        let data = this.ctx.request.body;
        for(var i=0;i<user_list.length;i++){
            if(data.id == user_list[i]['id']){
                user_list.splice(i,1,data);
            }
        }
        this.ctx.redirect("/fruits");
    }

    async show(){
        //表单无法设置put和delete提交，用show来代替删除
        let id = this.ctx.params.id;
        for(var i=0;i<user_list.length;i++){
            if(id == user_list[i]['id']){
                user_list.splice(i,1);
                break;
            }
        }
        this.ctx.redirect('/fruits');
    }
    getId(){
        let id = 0;
        for(var i=0;i<user_list.length;i++){
            id = user_list[i]['id'] > id ? user_list[i]['id'] : id;
        }
        return id;
    }
}

module.exports = FruitsController;